﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using EBAYVN.DOMAIN;
using EBAYVN.Util;
using System.Configuration;


namespace EBAYVN.DAO
{
    public class ConfigDao
    {
        public static readonly string Connectionstring = ConfigurationManager.AppSettings[Constants.SETTINGS_CONNECTION];
        private readonly EBAYVNDOMAINDataContext _db;
        protected static string _SESSION_ID = "_CRM_CONFIG_";
        protected Dictionary<string, string> _configsList = new Dictionary<string, string>();

        public ConfigDao()
        {
            _db = new EBAYVNDOMAINDataContext(Connectionstring);
            LoadConfigs();
        }

        private void LoadConfigs()
        {
            var oQuery = _db.Configs.ToList();
            _configsList.Clear();

            foreach (var t in oQuery)
                _configsList.Add(t.Name.ToUpper(), t.Value);

            HttpContext.Current.Session[_SESSION_ID] = _configsList;
        }

        public static string Value(string configName)
        {
            var resValue = "";
            try
            {
                var dictionary = HttpContext.Current.Session[_SESSION_ID] as Dictionary<string, string>;
                if (dictionary != null)
                    dictionary.TryGetValue(configName.ToUpper(), out resValue);
            }
            catch { }

            return resValue ?? "";
        }

        public void Save(string configName, string configValue)
        {
            configName = configName.ToUpper();
            if (_db.Configs.Count(w => w.Name == configName) == 0)
                _db.Configs.InsertOnSubmit(new Config { Name = configName, Value = configValue });
            else
            {
                var curConfig = _db.Configs.SingleOrDefault(w => w.Name == configName);
                if (curConfig != null) 
                    curConfig.Value = configValue;
            }
            _db.SubmitChanges();
        }
    }
}
